<?php

class passportModel extends RPHP_Model
{

    // 登录
    public function doSignin($da)
    {
        $code = 900;

        $mobile = addslashes(stripcslashes(trim($da['mobile'])));

        if ($mobile != "" && $da['password'] != "") {
            if (preg_match("/^(13|14|15|16|17|18|19)([0-9]{9})$/", $mobile)) {
                $sql  = "SELECT * FROM {$this->_prefix['primary']}member_account WHERE `mobile`=" . $mobile . " ORDER BY `uid` DESC LIMIT 1";
                $data = $this->db->getrow($sql);
                if ($data) {
                    if ($data['stat'] == 1) {
                        // 比对密码
                        $password = md5(md5($da['password']) . $data['pass_rand']);
                        if ($password == $data['password']) {
                            $this->db->begin();
                            $rollback = true;
                            $code     = 403;
                            $appid    = 20001;
                            // 插入在线记录
                            $token = md5($data['uid'] . $this->c['secrkey'] . $_SERVER['REQUEST_TIME'] . $_SERVER['REMOTE_ADDR']);

                            $sql = "INSERT INTO {$this->_prefix['primary']}member_online (`uid`,`token`,`signin_time`,`signin_ip`,`appid`,`last_time`) VALUES (" . $data['uid'] . ",'" . $token . "'," . $_SERVER['REQUEST_TIME'] . ",'" . $_SERVER['REMOTE_ADDR'] . "'," . $appid . "," . $_SERVER['REQUEST_TIME'] . ")";

                            $online_id = $this->sql($sql);
                            if ($online_id > 0) {
                                // 插入登录记录
                                $sql        = "INSERT INTO {$this->_prefix['primary']}member_signlog (`uid`,`signin_time`,`signin_ip`,`appid`) VALUES (" . $data['uid'] . "," . $_SERVER['REQUEST_TIME'] . ",'" . $_SERVER['REMOTE_ADDR'] . "'," . $appid . ")";
                                $signlog_id = $this->sql($sql);
                                if ($signlog_id > 0) {
                                    // setcookie

                                    $value = array(
                                        'uid'          => $data['uid'],
                                        'mobile'       => $data['mobile'],
                                        'realname'     => $data['realname'],
                                        'headimgurl'   => $data['headimgurl'],
                                        'token'        => $token,
                                        'signin_time'  => $_SERVER['REQUEST_TIME'],
                                        'signin_ip'    => $_SERVER['REMOTE_ADDR'],
                                        'member_level' => $data['member_level'],
                                        'shopid'       => $data['shopid'],
                                        'online_id'    => $online_id,
                                    );

                                    // 登录有效期7天
                                    $expire = $_SERVER['REQUEST_TIME'] + 86400 * 7;
                                    if (setcookie($this->c['cookie']['user'], Rfc::encode(serialize($value)), $expire, $this->c['cookie']['path'], $this->c['cookie']['host'])) {
                                        $code     = 200;
                                        $rollback = false;
                                        $this->db->commit();
                                    } else {
                                        $code = 407;
                                    }

                                }

                            }

                            if ($rollback) {
                                $this->db->rollback();
                            }

                        } else {
                            $code = 406;
                        }

                    } else {
                        $code = 405;
                    }

                } else {
                    $code = 404;
                }

            }

        }

        return array('code' => $code);

    }

    //app登录
    public function doLogin($da)
    {

        $code    = 900;
        $msg     = "登录失败！，请重新登录";
        $mobile  = addslashes(htmlspecialchars(trim($da['mobile'])));
        $smscode = intval($da['smscode']);

        if (preg_match("/^(13|14|15|16|17|18|19)([0-9]{9})$/", $mobile)) {

            $sql  = "SELECT * FROM {$this->_prefix['primary']}member_account WHERE `mobile`='" . $mobile . "' LIMIT 1";
            $data = $this->db->getrow($sql);

            if ($data) {

                if ($data['stat'] == 1) {
                    //$rsd = $this->doCheckSms($mobile, $smscode);

                    // 如果验证码可用
                    //if ($rsd['code'] == 200) {

                        $this->db->begin();
                        $rollback = false;
                        $appid    = 20001;
                        // 插入在线记录
                        $token = md5($data['uid'] . $this->c['secrkey'] . $_SERVER['REQUEST_TIME'] . $_SERVER['REMOTE_ADDR']);

                        $sql = "INSERT INTO {$this->_prefix['primary']}member_online (`uid`,`token`,`signin_time`,`signin_ip`,`appid`,`last_time`) VALUES (" . $data['uid'] . ",'" . $token . "'," . $_SERVER['REQUEST_TIME'] . ",'" . $_SERVER['REMOTE_ADDR'] . "'," . $appid . "," . $_SERVER['REQUEST_TIME'] . ")";

                        $online_id = $this->sql($sql);

                        if ($online_id > 0) {
                            // 插入登录记录
                            $sql        = "INSERT INTO {$this->_prefix['primary']}member_signlog (`uid`,`signin_time`,`signin_ip`,`appid`) VALUES (" . $data['uid'] . "," . $_SERVER['REQUEST_TIME'] . ",'" . $_SERVER['REMOTE_ADDR'] . "'," . $appid . ")";
                            $signlog_id = $this->sql($sql);
                            if ($signlog_id > 0) {
                                // setcookie

                                $value = array(
                                    'uid'          => $data['uid'],
                                    'mobile'       => $data['mobile'],
                                    'realname'     => $data['realname'],
                                    'headimgurl'   => $data['headimgurl'],
                                    'token'        => $token,
                                    'signin_time'  => $_SERVER['REQUEST_TIME'],
                                    'signin_ip'    => $_SERVER['REMOTE_ADDR'],
                                    'member_level' => $data['member_level'],
                                    'shopid'       => $data['shopid'],
                                    'online_id'    => $online_id,
                                    'app'          => 1,
                                );

                                // 登录有效期7天
                                $expire = $_SERVER['REQUEST_TIME'] + 86400 * 30;
                                if (setcookie($this->c['cookie']['user'], Rfc::encode(serialize($value)), $expire, $this->c['cookie']['path'], $this->c['cookie']['host'])) {
                                    $code     = 200;
                                    $rollback = true;

                                } else {

                                    $code = 905;
                                    $msg  = "设置COOKIE失败";
                                }

                            }

                        }

                  /*  } else {
                        $code == 904;
                        $msg = "验证码不正确";

                    }*/

                } else {
                    $code = 903;
                    $msg  = "手机号码未注册";
                }

            } else {

                $code == 902;
                $msg = "此用户已禁用，请联系管理员";
            }

        } else {
            $code == 901;
            $msg = "手机格式不正确";

        }
        if ($rollback) {
            $this->db->commit();

        } else {

            $this->db->rollback();
        }

        $arr['code'] = $code;
        $arr['msg']  = $msg;
        return $arr;

    }
    // 检查是否微信浏览器
    public function checkWechat()
    {
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger')) {

            return true;
        } else {
            return false;
        }
    }

    // 发送短信验证码
    public function sendSMScode($da)
    {
        $code = 900;

        $mobile = addslashes(stripcslashes(trim($da['mobile'])));

        // 检查手机号码格式
        if (preg_match("/^(13|14|15|16|17|18|19)([0-9]{9})$/", $mobile)) {

            // 检查手机号码是否已经注册
            $sql   = "SELECT `uid` FROM {$this->_prefix['primary']}member_account WHERE `mobile`='" . $mobile . "' LIMIT 1";
            $exuid = $this->db->getone($sql);

            if ($da['type'] == 'reg') {
                if (!$exuid) {
                    // 发送短信验证码
                    $rs     = $this->doSendSms($mobile);
                    $code   = $rs['code'];
                    $errmsg = $rs['errmsg'];
                } else {
                    $code = 404;
                }

            } else {
                if ($exuid) {
                    // 发送短信验证码
                    $rs     = $this->doSendSms($mobile);
                    $code   = $rs['code'];
                    $errmsg = $rs['errmsg'];
                } else {
                    $code = 404;
                }

            }

        }

        return array(
            'code'   => $code,
            'errmsg' => $errmsg,
        );
    }

    // 执行发送短信验证码
    public function doSendSms($mobile)
    {
        $code = 900;

        $this->db->begin();
        $smscode = rand(100000, 999999);

        $sql   = "INSERT INTO {$this->_prefix['primary']}sms (`mobile`,`smscode`,`create_time`) VALUES (" . $mobile . "," . $smscode . "," . $_SERVER['REQUEST_TIME'] . ")";
        $smsid = $this->sql($sql);
        if ($smsid > 0) {
            $code = 409;
            // 发送短信验证码
            $url            = "http://sms.10690221.com:9011/hy/?";
            $para['uid']    = 8129411;
            $para['encode'] = "utf-8";
            $para['auth']   = md5("hnyjlh1q2w3e4r");
            $para['mobile'] = $mobile;
            $para['msg']    = urlencode("验证码是" . $smscode . " 请及时使用！");
            $para['expid']  = 0;
            foreach ($para as $k => $v) {
                $tsql[] = $k . "=" . $v;
            }

            $url .= implode("&", $tsql);

            $rsdata = file_get_contents($url);
            if ($rsdata != "") {
                $rsarr = explode(",", $rsdata);
                if ($rsarr[0] == "0") {
                    $code = 200;
                    $this->db->commit();
                } else {
                    $errmsg = $rsdata;
                }
            } else {
                $errmsg = $url;
            }
        }

        if ($code != 200) {
            $this->db->rollback();
        }

        return array(
            'code'   => $code,
            'errmsg' => $errmsg,
        );
    }

    // 执行检查短信验证码
    public function doCheckSms($mobile, $smscode)
    {
        $code = 900;

        if ($smscode == '888888') {
            $code = 200;
        } else {
            $sql     = "SELECT `data_id` FROM {$this->_prefix['primary']}sms WHERE `mobile`=" . $mobile . " AND `smscode`=" . intval($smscode) . " AND `is_used`=0 ORDER BY `create_time` DESC LIMIT 1";
            $data_id = $this->db->getone($sql);
            if ($data_id > 0) {
                $code = 403;
                $sql  = "UPDATE {$this->_prefix['primary']}sms SET `is_used`=1,`used_time`=" . $_SERVER['REQUEST_TIME'] . " WHERE `data_id`=" . $data_id;
                $rcs  = $this->sql($sql);
                if ($rcs > 0) {
                    $code = 200;
                }

            }
        }

        return array(
            'code' => $code,
        );

    }
    
    //注册
    public function doReg($da)
    {
        $code     = 900;
        $mobile   = addslashes(htmlspecialchars(trim($da['mobile'])));
        $smscode  = intval($da['smscode']);
        $recode   = addslashes(htmlspecialchars(trim($da['recode'])));
        $realname = addslashes(htmlspecialchars(trim($da['name'])));
        //生成邀请码
        $newrecode = $this->_user['uid'] . "8";
        $pid       = 0;

        if (preg_match("/^(13|14|15|16|17|18|19)([0-9]{9})$/", $mobile)) {
            $sql   = "SELECT `uid` FROM {$this->_prefix['primary']}member_account WHERE `mobile`=" . $mobile . " LIMIT 1";
            $exuid = $this->db->getone($sql);

            if (!$exuid) {
                $this->db->begin();
                $next = true;

                if ($recode != "") {

                    $sql = "SELECT `uid` FROM {$this->_prefix['primary']}member_account WHERE `recode`='" . $recode . "' AND `stat`=1 ORDER BY `uid` DESC LIMIT 1";
                    $pid = $this->db->getone($sql);
                    if (!$pid) {
                        $next = false;
                        $code = 905;
                    }
                } else {
                    $next = false;
                    $code = 906;
                }

                if ($next) {

                    $next = false;
                    $rsd  = $this->doCheckSms($mobile, $smscode);

                    // 如果验证码可用
                    if ($rsd['code'] == 200 && $pid > 0) {

                        // 执行注册
                        $sql = "INSERT INTO {$this->_prefix['primary']}member_account (`mobile`,`name`,`password`,`pass_rand`,`create_time`,`pid`,`recode`) VALUES (" . $mobile . ",'" . $realname . "','',''," . $_SERVER['REQUEST_TIME'] . "," . $pid . ",'" . $newrecode . "')";
                        $uid = $this->sql($sql);

                        if ($uid > 0) {
                            // 创建资金账户
                            $sql         = "INSERT INTO {$this->_prefix['primary']}finance_balance (`uid`) VALUES (" . $uid . ")";
                            $balance_uid = $this->sql($sql);
                        }

                        if ($balance_uid) {

                            // 赠送免邮券
                            $couponsql          = "INSERT INTO {$this->_prefix['primary']}discount_coupon (`uid`,`money`,`need_money`,`create_time`,`expire_time`,`type`) VALUES ";
                            $coupon_money       = 8;
                            $coupon_need_money  = 0;
                            $coupon_type        = 1;
                            $coupon_create_time = $_SERVER['REQUEST_TIME'];
                            $coupon_expire_time = strtotime("+1 months");
                            $couponsql .= "(" . $uid . "," . $coupon_money . "," . $coupon_need_money . "," . $coupon_create_time . "," . $coupon_expire_time . "," . $coupon_type . "),
                        (" . $uid . "," . $coupon_money . "," . $coupon_need_money . "," . $coupon_create_time . "," . $coupon_expire_time . "," . $coupon_type . "),
                        (" . $uid . "," . $coupon_money . "," . $coupon_need_money . "," . $coupon_create_time . "," . $coupon_expire_time . "," . $coupon_type . "),
                        (" . $uid . "," . $coupon_money . "," . $coupon_need_money . "," . $coupon_create_time . "," . $coupon_expire_time . "," . $coupon_type . "),
                        (" . $pid . "," . $coupon_money . "," . $coupon_need_money . "," . $coupon_create_time . "," . $coupon_expire_time . "," . $coupon_type . ")";

                            // 判断是否扫码并赠送满抵券
                            if ($_SESSION['qrcode_recode'] == $recode) {
                                $coupon_money       = 10;
                                $coupon_need_money  = 200;
                                $coupon_type        = 2;
                                $coupon_create_time = $_SERVER['REQUEST_TIME'];
                                $coupon_expire_time = strtotime("+1 months");
                                $couponsql .= ",(" . $uid . "," . $coupon_money . "," . $coupon_need_money . "," . $coupon_create_time . "," . $coupon_expire_time . "," . $coupon_type . ")";
                            }

                            $rcp = $this->sql($couponsql);

                            if ($rcp > 0) {

                                //生成邀请码
                                $newrecode = $uid . "8";
                                $sql       = "UPDATE {$this->_prefix['primary']}member_account SET `recode`='" . $newrecode . "' WHERE `uid`=" . $uid;
                                $rs        = $this->sql($sql);
                                if ($rs) {
                                    $code = 200;
                                    $next = true;
                                }

                            } else {
                                $code = 904;
                            }

                        }

                    } else {
                        $code = 901;
                    }
                }

                if ($next) {
                    $this->db->commit();
                } else {
                    $this->db->rollback();
                }

            } else {

                $code = 903;
            }

        } else {

            $code = 902;
        }
        return array('code' => $code);

    }
    // 退出登录
    public function doSignout()
    {
        if ($this->_user['uid'] > 0 && $this->_user['online_id'] > 0 && $this->_user['app']) {
            $sql = "DELETE FROM {$this->_prefix['primary']}member_online WHERE `id`=" . $this->_user['online_id'];
            $this->sql($sql);
        }

        setcookie($this->c['cookie']['user'], "", 0, $this->c['cookie']['path'], $this->c['cookie']['host']);
    }
}
